#!/usr/bin/env julia
"""
Minimal standalone test for BUFRReader module - no dependencies
"""

using Dates
using Printf

println("="^70)
println("BUFRReader Minimal Test")
println("="^70)

# Test real PrepBUFR file reading
println("\n[Test] Real PrepBUFR File Binary Parsing")
prepbufr_file = "/home/docker/comgsi/tutorial/case_data/2018081212/obs/rap.t12z.prepbufr.tm00"

if isfile(prepbufr_file)
    println("  File found: $prepbufr_file")
    file_size = filesize(prepbufr_file)
    println("  File size: $file_size bytes ($(round(file_size/1024/1024, digits=2)) MB)")

    # Read file
    file_data = read(prepbufr_file)

    # Count BUFR messages
    pos = 1
    msg_count = 0
    total_length = 0

    while pos < length(file_data) - 8
        # Look for BUFR header
        if pos + 4 <= length(file_data) &&
           file_data[pos] == UInt8('B') &&
           file_data[pos+1] == UInt8('U') &&
           file_data[pos+2] == UInt8('F') &&
           file_data[pos+3] == UInt8('R')

            msg_count += 1

            # Read message length (bytes 5-7, 24-bit big-endian)
            if pos + 7 <= length(file_data)
                msg_length = Int(file_data[pos+4]) << 16 |
                           Int(file_data[pos+5]) << 8 |
                           Int(file_data[pos+6])

                if msg_length > 0 && pos + msg_length <= length(file_data)
                    total_length += msg_length

                    if msg_count <= 5
                        println("  Message $msg_count: $msg_length bytes at position $pos")
                    end

                    pos += msg_length
                else
                    pos += 1
                end
            else
                pos += 1
            end
        else
            pos += 1
        end
    end

    println("\n  ✓ BUFR File Statistics:")
    println("    Total BUFR messages found: $msg_count")
    println("    Total message length: $total_length bytes")
    println("    Average message size: $(round(total_length/msg_count, digits=1)) bytes")
    println("    Coverage: $(round(100.0*total_length/file_size, digits=1))% of file")

    # Estimate observations
    # Typical PrepBUFR: ~100-500 bytes per observation subset
    est_obs_low = total_length ÷ 500
    est_obs_high = total_length ÷ 100
    println("\n  Estimated observations: $est_obs_low to $est_obs_high")

    println("\n  Comparison with Fortran GSI:")
    println("    Fortran GSI gdas1.t12z.prepbufr: 230,518 total, 63,580 after QC")
    println("    This is a different file (rap.t12z.prepbufr) so counts will vary")

    println("\n  ✓ Binary parsing successful")
    println("  ✓ BUFR format detected and validated")

    # Now test the actual BUFRReader implementation
    println("\n[Test] BUFRReader Module Integration")

    # Define minimal ObservationData type
    struct ObservationData
        obs_values::Vector{Float64}
        obs_errors::Vector{Float64}
        obs_locations::Matrix{Float64}
        obs_types::Vector{Int}
        obs_times::Vector{DateTime}
        qc_flags::Vector{Int}
        metadata::Dict{String,Any}

        function ObservationData(values, errors, locations, types, times, qc_flags; metadata=Dict{String,Any}())
            nobs = length(values)
            @assert length(errors) == nobs
            @assert size(locations, 1) == nobs
            @assert size(locations, 2) == 3
            @assert length(types) == nobs
            @assert length(times) == nobs
            @assert length(qc_flags) == nobs
            new(values, errors, locations, types, times, qc_flags, metadata)
        end
    end

    # Create minimal DataIO namespace
    module DataIO
        using ..Main: ObservationData
        export ObservationData
    end

    # Include BUFRReader
    include("../src/DataIO/BUFRReader.jl")
    using .BUFRReader

    println("  ✓ BUFRReader module loaded")

    # Test synthetic generation
    obs_synthetic = BUFRReader.generate_synthetic_observations("test.bufr")
    println("  ✓ Synthetic observations: $(length(obs_synthetic.obs_values))")
    println("    Types: ps=$(obs_synthetic.metadata["n_ps"]), t=$(obs_synthetic.metadata["n_t"]), " *
            "q=$(obs_synthetic.metadata["n_q"]), uv=$(obs_synthetic.metadata["n_uv"])")

    # Test real file reading
    println("\n  Reading actual PrepBUFR file...")
    obs_real = BUFRReader.read_prepbufr(prepbufr_file)
    nobs = length(obs_real.obs_values)
    println("  ✓ Read $nobs observations")

    # Validate
    @assert length(obs_real.obs_errors) == nobs
    @assert size(obs_real.obs_locations, 1) == nobs

    lons = obs_real.obs_locations[:, 1]
    lats = obs_real.obs_locations[:, 2]
    pressures = obs_real.obs_locations[:, 3]

    println("\n  Data ranges:")
    println("    Longitude: [$(round(minimum(lons), digits=1)), $(round(maximum(lons), digits=1))]")
    println("    Latitude: [$(round(minimum(lats), digits=1)), $(round(maximum(lats), digits=1))]")
    println("    Pressure: [$(round(minimum(pressures), digits=1)), $(round(maximum(pressures), digits=1))] hPa")

    # Summary
    summary = BUFRReader.summarize_observations(obs_real)

    if haskey(summary, "type_counts") && !isempty(summary["type_counts"])
        println("\n  Observation types:")
        for (type_code, count) in sort(collect(summary["type_counts"]))
            type_name = BUFRReader.get_observation_type_name(type_code)
            pct = round(100.0 * count / nobs, digits=1)
            println("    $type_name ($type_code): $count ($pct%)")
        end
    end

    if haskey(summary, "qc_counts") && !isempty(summary["qc_counts"])
        println("\n  QC distribution:")
        for (qc, count) in sort(collect(summary["qc_counts"]))
            qc_desc = qc == 0 ? "good" : qc == 1 ? "suspect" : qc == 2 ? "questionable" : "bad"
            pct = round(100.0 * count / nobs, digits=1)
            println("    QC=$qc ($qc_desc): $count ($pct%)")
        end
    end

    println("\n  ✓ All validation checks passed")

else
    println("  ⚠ PrepBUFR file not found: $prepbufr_file")
    println("  Expected location: /home/docker/comgsi/tutorial/case_data/2018081212/obs/")
end

println("\n" * "="^70)
println("Test Complete!")
println("="^70)
